package com.xzbd.restclient.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.xzbd.restclient.domain.User;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/rest-client")
public class RestClientController {

    @GetMapping("/get/{id}")
    public Map<String, Object> getTest(@RequestParam String name, @PathVariable("id") Integer id) {
        Map<String, Object> resultMap = buildRestMap();
        resultMap.put("in", "name : " + name + " , id : " + id);
        resultMap.put("out", "hello ： " + name);
        return resultMap;
    }

    @GetMapping("/get/headers")
    public Map<String, Object> headers(HttpServletRequest request) {
        Map<String, Object> resultMap = buildRestMap();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hName = headerNames.nextElement();
            resultMap.put(hName, request.getHeader(hName));
        }
        return resultMap;
    }

    @PutMapping("/put")
    public Map<String, Object> putTest(@RequestParam String name) {
        Map<String, Object> resultMap = buildRestMap();
        resultMap.put("method", "PUT");
        resultMap.put("in", name);
        return resultMap;
    }

    @DeleteMapping("/del")
    public Map<String, Object> deleteTest(@RequestParam String name) {
        Map<String, Object> resultMap = buildRestMap();
        resultMap.put("msg", "你删除了用户： " + name);
        return resultMap;
    }

    @PostMapping("/post/user")
    public Map<String, Object> postTest(@RequestBody User user) {
        Map<String, Object> resultMap = buildRestMap();
        resultMap.put("用户信息", user);
        return resultMap;
    }

    @PostMapping("/post/file")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        Map<String, Object> resultMap = buildRestMap();
        resultMap.put("msg", "上传文件成功！");
        resultMap.put("fileName", file.getOriginalFilename());
        resultMap.put("fileSize", file.getSize());
        return resultMap;
    }

    /**
     * 构建空Map
     * 
     * @return
     */
    private Map<String, Object> buildRestMap() {
        return new HashMap<>();
    }

}
